import { Rectangle } from './Rectangle'
/**
 * 水管，必须要移动
 */
const gameWidth = 800 //  水管默认是在地图右外边
export class Pipe extends Rectangle{
  constructor(height,top,speed,dom) {
    super(52,height,gameWidth,top,speed,0,dom)
  }
  onMove() {
    // 如果当前水管dom在外侧已经一半了，删除dom
    if (this.left < - this.width / 2) {
      this.dom.remove()
    }
  }
}

function getRandom(min,max) {
  return Math.floor(Math.random() * (max - min) + min)
}

const mapHeight = 488 // 地图高度
const spaceHeight = 150 // 默认通过的空隙高度
const minHeight = 80 // 水管最小高度
const maxHeight = mapHeight - minHeight - spaceHeight // 水管最大高度


export class Pair {
  constructor(speed,gameDom) {
    this.upHeight = getRandom(minHeight,maxHeight)  // 上水管高度
    this.downHeight = mapHeight - spaceHeight - this.upHeight // 下水管高度
    this.top = 0  
    // 生成两个dom元素
    const domUp = document.createElement("div")
    domUp.className = 'pipe up'
    const domDown = document.createElement("div")
    domDown.className = 'pipe down'

    this.pipeUp = new Pipe(this.upHeight,0,speed,domUp)
    this.pipeDown = new Pipe(this.downHeight,spaceHeight + this.upHeight,speed,domDown)

    // 把这两个dom水管加入到game中
    gameDom.appendChild(domUp)
    gameDom.appendChild(domDown)
  }
  move(duration) {
    this.pipeUp.move(duration)
    this.pipeDown.move(duration)
  }
  isCollase() {
    return this.pipeUp.x <  -this.pipeUp.width
  }
}

export class PairList {
  constructor(speed,dom) {
    this.timer = null
    this.pairs = []
    this.speed = speed
    this.dom = dom
  }
  startProducter() {
    if (this.timer) {
      return
    }
    let pre = 0
    let step = (timestamp) => {
      this.timer = timestamp
      if (timestamp - pre > 2000) {
        pre = timestamp
        let pair = new Pair(this.speed,this.dom)
        this.pairs.push(pair)
      }
      for (let i = 0; i < this.pairs.length; i ++) {
        if (this.pairs[i].isCollase()) {
          this.pairs.splice(i,1)
          i --
        }
      }
      requestAnimationFrame(step)
    }
    requestAnimationFrame(step)
  }
  stopProducter() {
    clearInterval(this.timer)
    this.timer = null
  }
}
